package com.etc.service.impl;

import com.etc.dao.CinemaDao;
import com.etc.dao.MovieDao;
import com.etc.entity.Cinema;
import com.etc.entity.Movie;
import com.etc.service.MovieService;
import com.etc.util.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/5/21.
 */
@Service
public class MovieServiceImpl implements MovieService {
    @Autowired
    private MovieDao movieDao;
    @Autowired
    private CinemaDao cinemaDao;

    /*
    随机显示正在上映的电影
     */
    @Override
    public List<Movie> findByMstatusOrderByMgradeAsc() {
        List<Movie> list = movieDao.findByMstatusOrderByMgradeDesc(1);
        Collections.shuffle(list);
        return list;
    }

    /*
    显示即将上映的电影
     */
    @Override
    public List<Movie> findByMstatus() {
        return movieDao.listRecentMovie();
    }

    /*
    显示正在上映的电影 按评分 倒序
     */
    @Override
    public List<Movie> findByMstatusOrderByMgradeDesc() {
        return movieDao.findByMstatusOrderByMgradeDesc(1);
    }

    @Override
    public Movie findByMid(Integer mid) {
        return movieDao.findOne(mid);
    }

    /*
    传入 MM-dd 的String 格式日期   转换成Date类型 传入Dao
     */
    @Override
    public List<Cinema> findByMidAndMstartime(Integer mid, String playDate) {
        try {
            String playDate01 = playDate.replaceAll("月", "-");
            String playDate02 = playDate01.replaceAll("日", "");
            Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2019-" + playDate02);
            return cinemaDao.findByMidAndMstartime(mid, date);
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public List<Movie> FindMoviceByNameForSearch(String name) {
        return movieDao.FindMovieByNameForSerach(name);
    }

    @Override
    public PageData<Movie> getPageData(Integer page, Integer limit, String content) {
        Pageable pageable = new PageRequest(page, limit);
        Page<Movie> userPage = movieDao.findByLike(content, pageable);
        List<Movie> list = userPage.getContent();
        int count = (int) userPage.getTotalElements();
        PageData pd = new PageData(list, count, limit, page);
        return pd;
    }

    @Override
    public boolean updateMovie(Movie movie) {
        try {
            movieDao.save(movie);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    @Override
    public boolean deleteMovie(Integer mid) {
        try {
            movieDao.delete(mid);
            return true;
        } catch (Exception e) {
            return false;
        }


    }


}
